import { _decorator, Vec2 } from 'cc';
import { ENTITY_STATE_ENUM } from '../../Enum';
import { InputManager } from '../../Base/InputManager';
import { AirState } from './AirState';
const { ccclass, property } = _decorator;

@ccclass('JumpState')
export class JumpState extends AirState {
    onEnter(): void {
        super.onEnter(); 
        
    }
    update(deltaTime: number): void {

        // 松开跳跃键
        if (!InputManager.Instance.pressJump) {
            this.fsm.setGravityScale(this.fsm.player.data.gravityScale * this.fsm.player.data.jumpCutGravityMult);
            this.rb.linearVelocity = new Vec2(
                this.rb.linearVelocity.x,
                Math.max(this.rb.linearVelocity.y, -this.fsm.player.data.maxFallSpeed)
            );
        }else if (Math.abs(this.rb.linearVelocity.y) < this.fsm.player.data.jumpHangTimeThreshold) {
            this.fsm.setGravityScale(this.fsm.player.data.gravityScale * this.fsm.player.data.jumpHangGravityMult);
        }   
        
        // 跳跃下落检测
        if (this.rb.linearVelocity.y < 0) {
            this.fsm.transit(ENTITY_STATE_ENUM.FALL)
        }
        super.update(deltaTime);
        
    }

    *Coroutine(): Generator {
        // yield null;

        this.fsm.setGravityScale(this.fsm.player.data.gravityScale);

        this.fsm.lastPressedJumpTime = 0;
        this.fsm.lastOnGroundTime = 0;

        let force = this.fsm.player.data.jumpForce;
        // 完全抵消下落速度
        if (this.rb.linearVelocity.y < 0) {
            this.rb.linearVelocity = new Vec2(this.rb.linearVelocity.x, 0);
        }
        
        this.rb.applyForceToCenter(new Vec2(0, force), true);
        console.log("jump:",force);
        

    }
    IsCoroutine(): boolean {
        return true;
    }

    onExit(): void {
        super.onExit(); 
    }

    canTransit(to: ENTITY_STATE_ENUM): boolean {
        if (to === this.id) return false;
        if (to === ENTITY_STATE_ENUM.FALL) return true;
        if (to === ENTITY_STATE_ENUM.IDLE && this.fsm.lastOnGroundTime > 0) return true; 
        if (to === ENTITY_STATE_ENUM.RUN && this.fsm.lastOnGroundTime > 0) return true;
        return true;
    }
}


